<template>
  <div class="min-h-screen bg-gradient-to-br">

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">

        <!-- 左侧区域 (25%) -->
        <div class="lg:col-span-3 space-y-6 sticky lg:top-36 self-start">
          <!-- 翻转容器 -->
          <div class="flip-card-container" :style="{ height: containerHeight }">
            <div class="flip-card-inner" :class="{ 'is-flipped': isEditing }">
              <div class="flip-card-front" ref="frontCard">
                <UserInfoCard
                    :user="userInfo"
                    :userId="userId"
                    :isCurrentUser="isCurrentUser"
                    @follow="handleFollowUser"
                    @edit-profile="startEditing"
                    @show-list="handleShowList"
                />
              </div>
              <div class="flip-card-back" ref="backCard">
                <UserProfileEditor
                    :user="userInfo"
                    @save="saveUserProfile"
                    @cancel="cancelEditing"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 中间区域 (50%) -->
        <div class="lg:col-span-6 space-y-6">
          <!-- 帖子列表 -->
          <PostList v-if="activeView === 'posts'" pageType="user" :userId="userId" :communityId="null"/>
          <ConcernList v-else-if="activeView === 'following'" :userId="userId"/>
          <FollowersList v-else-if="activeView === 'followers'" :userId="userId"/>
        </div>

        <!-- 右侧区域 (25%) -->
        <div class="lg:col-span-3 space-y-6 sticky lg:top-36 self-start max-h-[calc(100vh-5rem)] overflow-y-auto">
          <!-- 看过我列表 -->
          <ViewersList/>
          <!-- 我加入的社区列表 -->
          <JoinedCommunities/>
        </div>

      </div>
    </main>

  </div>
</template>

<script>


import PostList from "@/components/PostList.vue";
import UserInfoCard from "@/components/UserInfoCard.vue";
import ViewersList from "@/components/ViewersList.vue";
import JoinedCommunities from "@/components/JoinedCommunities.vue";
import UserProfileEditor from "@/components/UserProfileEditor.vue";
import FollowersList from "@/components/FollowersList.vue";
import ConcernList from "@/components/ConcernList.vue";
import {mapState} from "vuex";

export default {
  name: "User",
  components: {ConcernList, PostList, UserInfoCard, ViewersList, JoinedCommunities, UserProfileEditor, FollowersList},
  data() {
    return {
      userId: null,
      isEditing: false,
      containerHeight: 'auto', // 用于动态控制容器高度
      activeView: 'posts',
      userInfo: {
        nickname: "社区小能手",
        avatar: "https://tse3-mm.cn.bing.net/th/id/OIP-C.THDXyIcJ0GrMnO58H4FzpQHaHa?w=187&h=187&c=7&r=0&o=7&dpr=1.1&pid=1.7&rm=3",
        backgroundImage: "https://ts4.tc.mm.bing.net/th/id/OIP-C.Hbkk9AkInuzpK6UyPKXyYQHaEK?rs=1&pid=ImgDetMain&o=7&rm=3",
        schoolName: "软件工程大学",
        age: 22,
        gender: "male",
        isMember: true,
        enrollmentDate: "2021-09", // 更新为年月格式
        major: "计算机科学与技术",
        class: "软件2101班", // 新增班级字段
        hometown: "北京",
        ipCity: "上海",
        postCount: 128,
        likeCount: 3642,
        commentCount: 891,
        followingCount: 10,
        followerCount: 20,
        bio: "热爱编程与生活的前端开发者，欢迎一起交流学习！",
        joinDate: "2023-04-01",
        birthday: "2002-01-01", // 添加生日字段，用于编辑表单
        tags: ["Vue", "摄影", "旅行", "猫咪爱好者"]
      }
    };
  },
  computed: {
    ...mapState({
      currentUserId: state => state.userId
    }),
    // 判断当前查看的用户是否是登录用户自己
    isCurrentUser() {
      return this.userId === this.currentUserId;
    }
  },
  mounted() {
    this.updateContainerHeight();
    window.addEventListener('resize', this.updateContainerHeight);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.updateContainerHeight);
  },
  created() {
    // 从路由参数中获取用户ID
    this.loadUserData();
  },
  watch: {
    // 监听路由参数变化，当用户点击不同的头像时更新页面内容
    '$route.query.userId': function () {
      this.loadUserData();
      // 如果正在编辑，切换到其他用户时退出编辑模式
      if (this.isEditing) {
        this.isEditing = false;
      }
    },
    isEditing() {
      this.updateContainerHeight();
    }
  },
  methods: {
    // 动态更新容器高度以适应内容
    updateContainerHeight() {
      this.$nextTick(() => {
        try {
          const front = this.$refs.frontCard;
          // 始终以 UserInfoCard 的高度为基准，保持容器大小固定
          if (front) {
            this.containerHeight = `${front.scrollHeight}px`;
          }
        } catch (e) {
          console.error("Failed to update container height:", e);
        }
      });
    },

    // 加载用户数据
    loadUserData() {
      // 从路由query参数中获取用户ID，支持直接URL访问
      this.userId = this.$route.query.userId || this.$route.params.userId;
      console.log("加载用户ID:", this.userId);
      console.log("当前登录用户ID:", this.currentUserId);

      // TODO: 在实际应用中，这里应该调用API获取用户数据
      // 例如: this.fetchUserData(this.userId);

      // 在这个示例中，我们使用的是静态数据
      // 如果需要，可以根据userId加载不同的用户数据
    },

    handleShowList(view) {
      this.activeView = view;
    },

    handleFollowUser(userId) {
      console.log("关注用户:", userId);
      // TODO: 实现关注用户的API调用
      // 这里可以添加关注用户的逻辑，例如调用API
    },

    // 开始编辑个人资料
    startEditing() {
      // 只有当前用户才能编辑自己的资料
      if (this.isCurrentUser) {
        this.isEditing = true;
      }
    },

    // 保存编辑后的个人资料
    saveUserProfile(updatedUser) {
      // 更新用户信息
      this.userInfo = {...updatedUser};

      // TODO: 在实际应用中，这里应该调用API将更新后的用户信息保存到服务器
      console.log("保存用户资料:", updatedUser);

      // 改变状态，watcher会自动更新高度
      this.isEditing = false;

      // 显示成功提示
      this.$nextTick(() => {
        // 如果有通知系统，可以在这里显示保存成功的通知
        alert("个人资料更新成功！");
      });
    },

    // 取消编辑
    cancelEditing() {
      // 改变状态，watcher会自动更新高度
      this.isEditing = false;
    }
  }
};
</script>

<style scoped>
/* 新的翻转卡片容器样式 */
.flip-card-container {
  perspective: 1500px;
  position: relative;
  width: 100%;
  /* 高度过渡不再需要，因为高度是固定的 */
}

.flip-card-inner {
  position: absolute;
  width: 100%;
  height: 100%;
  transform-style: preserve-3d;
  transition: transform 0.7s cubic-bezier(0.65, 0, 0.35, 1); /* 更优雅的翻转曲线 */
  will-change: transform; /* 性能优化提示 */
}

.flip-card-inner.is-flipped {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden; /* 兼容 Safari */
}

.flip-card-back {
  transform: rotateY(180deg);
}
</style>

